<template>
  <el-dialog
    v-model="showDialog"
    v-if="showDialog"
    title="选择收藏夹 "
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    @close="resetFolderDialog"
  >
    <el-form :model="giveLikeData">
      <el-form-item label="收藏夹名称" required>
        <el-select v-model="value" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
         
    </el-form>
    <template #footer>
      <el-button @click="showDialog = false">取消</el-button>
      <el-button type="primary" @click="saveGiveLike">确定</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import * as collectApi from '@/api/collection';


const emit = defineEmits(['giveLikeSuccess']);

const showDialog = ref(false);
const giveLikeData = reactive({ id:0,name:'' });
const options = ref<{id: number, name: string}[]>([]);
const value = ref();
const foldersId = ref<number | string>(0);

const openDialog = (id:number|string) => {
  foldersId.value = id;
  showDialog.value = true;
  getGiveLike();
};

defineExpose({ openDialog });

// 关闭选择收藏夹弹窗
const resetFolderDialog = () => {
  showDialog.value = false;
  value.value = undefined;
};
// 确认选择收藏夹
const saveGiveLike = async() => {
  if (!value.value) {
    ElMessage.warning('请选择收藏夹');
    return;
  }
  try{
    await collectApi.favorite({ id:foldersId.value,folder_id:value.value });
    emit('giveLikeSuccess');
    resetFolderDialog();
    ElMessage.success('收藏成功');
  } catch (error) {
    console.error(error);
    ElMessage.error('收藏失败');
  }
    
};

const getGiveLike = async() => {
  try {
    const res = await collectApi.getFoldersList({ page: 1, size: 50 });
    options.value = res.data;
  } catch (error) {
    console.error(error);
    ElMessage.error('获取收藏夹列表失败');
  }
};

</script>